<?php
/**
 * Description of societe
 *
 * @author Gmax
 */
class modules_societe_societe extends modele{
    public static $_table = 'societe';
    public $type = 'societe';
    
    private $_id = 0;
    private $_nom = "";
    private $_siret = "";
    private $_adresse_id;
    private $_adresse = null;
    private $_media_id = 0;
    private $_media = null;
    private $_web = "";
    private $_email = "";
    private $_phone = "";
    private $_effectifs = 0;
    private $_date_crea = "0000-00-00 00:00:00";
    
    private $_employes = null;
    
    function __construct($id=null){
        if($id!==null){
            $this->_id = $id;
            $this->_constructObject();
        }
    }
    
    private function _constructObject(){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.* ';
        $sqlQuery .= 'FROM '.self::getTable().' AS t ';
        $sqlQuery .= 'WHERE t.id='.$this->_id.' ';
        $sqlQuery .= 'LIMIT 1';
        $datas = $this->_getOneResult($sqlQuery);
        if($datas){
            $this->_id = $datas['id'];
            $this->_nom =  $this->outputFormat($datas['nom']);
            $this->_siret =  $datas['siret'];
            $this->_adresse_id =  $datas['adresse_id'];
            $this->_media_id =  $datas['media_id'];
            $this->_web =  $datas['web'];
            $this->_email =  $datas['email'];
            $this->_phone =  $datas['phone'];
            $this->_effectifs =  $datas['effectifs'];
            $this->_date_crea =  $datas['date_crea'];
        }
    }
    public function setId($id){
      $this->_id = $id;
    }
    public function getId(){
        return $this->_id;
    }
    public function getNom($input=false){
        if($input)return $this->inputFormat($this->_nom);
        else return $this->outputFormat($this->_nom);
    }
    public function getSiret(){
        return $this->_siret;
    }
    public function getWeb(){
        return $this->_web;
    }
    public function getEmail(){
        return $this->_email;
    }
    public function getPhone(){
        return $this->_phone;
    }
    public function getEffectifs(){
        return $this->_effectifs;
    }
    public function getDateCrea(){
        return $this->_date_crea;
    }
    /**
     * renvoi l'identifiant de l'avatar
     * @return int
     */
    public function getMediaId(){
        return (isset($this->_media_id)&&$this->_media_id>0)?$this->_media_id:0;
    }
    /**
     * retourne l'avatar
     * @return \modele_media
     */
    public function getMedia(){
        if($this->_media===null){
            if($this->getMediaId()>0) $this->_media = new modele_media($this->_media_id);
            else $this->_media = new modele_media();
        }
        return $this->_media;
    }
    /**
     * indique si le membre a un avatar
     * @return boolean
     */
    public function haveMedia(){
        return ($this->getMediaId()>0)?true:false;
    }
    /**
     * ajoute un avatar
     * @param int $mediaId
     * @return boolean
     */
    public function addMedia($mediaId){
        $this->setDatas(array('_media_id'=>$mediaId));
        $this->_media = new modele_media($mediaId);
        $sqlQueryMedia = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryMedia .= 'media_id='.$this->getMedia()->getId().' ';
        $sqlQueryMedia .= 'WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQueryMedia,false);
        return true;
    }
    /**
     * suprime l'avatar
     * @return boolean
     */
    public function removeMedia($mediaId=0){
        $mediaToDelete = $this->getMedia();
        $this->_media_id = 0;
        $this->_media = null;
        $sqlQueryMedia = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryMedia .= 'media_id=NULL ';
        $sqlQueryMedia .= 'WHERE id='.$this->getId();
        bdd_sql::doSql($sqlQueryMedia,false);
        $mediaToDelete->delete();
        return true;
    }
    /**
     * retourne l'identifiant de l'objet adresse
     * @return int
     */
    public function getAdresseId(){
        return (isset($this->_adresse_id)&&$this->_adresse_id>0)?$this->_adresse_id:0;
    }
    /**
     * retourne l'objet modele_adresse
     * @return \modele_adresse
     */
    public function getAdresse(){
        if(isset($this->_adresse)){
            return $this->_adresse;
        }elseif($this->getAdresseId()>0){
            $this->_adresse = new modele_adresse($this->getAdresseId());
            return $this->_adresse;
        }else{
            return null;
        }
    }
    /**
     * retourne l'identifiant de région
     * @return int
     */
    public function getRegionId(){
        if($this->getAdresse()!=null){
            return $this->getAdresse()->getRegionId();
        }
        return 0;
    }
    /**
     * retourne l'objet modele_region
     * @return \modele_region|null
     */
    public function getRegion(){
        if($this->getRegionId()>0){
            return new modele_region($this->getRegionId());
        }
        return null;
    }
    
    /**
     * renvoi le tableau des employés de la société
     * @param int $start
     * @param int $limit
     * @return \modules_societe_employe
     */
    public function getEmployes($start=0,$limit=0){
        if($this->_employes === null ){
            $sqlQuery = 'SELECT ';
            $sqlQuery .= 'us.user_id AS user_id ';
            $sqlQuery .= 'FROM '.PWE::getPrefixBdd().'user_societe AS us ';
            $sqlQuery .= 'LEFT JOIN '.modele_user::getTable().' AS u ON u.id=us.user_id ';
            $sqlQuery .= 'WHERE us.societe_id='.$this->getId().' ';
            $sqlQuery .= 'ORDER BY u.nom';
            
            if($limit>0){
                $sqlQuery .= ' LIMIT '.$start.','.$limit;
            }

            $retour = array();

            $results = bdd_sql::doSql($sqlQuery, true);
            if($results['count']>0){
                foreach($results['results'] as $datas){
                    $employe = new modules_societe_employe($datas['user_id'],$this->getId());
                    $retour[] = $employe;
                }                
                $this->_employes = $retour;
            }
            return $retour;
        }else{
            return $this->_employes;
        }
    }
    /**
     * ajoute un employé
     * @param \modules_societe_employe $employe
     * @return array [success,error]
     */
    public function addEmploye($employe){
        $retour = array('success'=>false,'error'=>'null');
        if($employe!==null&&$employe->getId()>0){
            $sqlQuery = 'REPLACE INTO '.PWE::getPrefixBdd().'user_societe (user_id,societe_id,`post`) VALUES ('.$employe->getId().','.$this->getId().',"'.$employe->getPost(true).'")';
            $result = bdd_sql::doSql($sqlQuery,false);
            if($result['count']>0){
                $retour['success'] = true;
                if($this->_employes === null ){
                    $this->_employes = array($employe);
                }else{
                    $this->_employes[] = $employe;
                }
            }else{
                $retour['error'] = bdd_sql::$LASTERROR;
            }
        }
        return $retour;
    }
    
    /**
     * meise à jour du post de l'employé
     * @param \modules_societe_employe $employe
     * @param string $post
     */
    public function updateEmploye($employe,$post){
        $employe->setDatas(array('post'=>$post));
        $sqlQuery = 'UPDATE '.PWE::getPrefixBdd().'user_societe SET post="'.$employe->getPost(true).'" WHERE user_id='.$employe->getId().' AND societe_id='.$this->getId();
        bdd_sql::doSql($sqlQuery,false);
    }
    
    /**
     * supprime un employé
     * @param \modules_societe_employe $employe
     * @return array [success,error]
     */
    public function removeEmploye($employe){
        $retour = array('success'=>false,'error'=>'null');
        if($employe!==null&&$employe->getId()>0){
            $sqlQuery = 'DELETE FROM '.PWE::getPrefixBdd().'user_societe WHERE user_id='.$employe->getId().' AND societe_id='.$this->getId();
            $results = bdd_sql::doSql($sqlQuery,false);
            if($results['count']>0){
                $retour['success'] = true;
                if($this->_employes !== null ){
                    $idx = array_search($employe, $this->_employes);
                    if($idx!==false){
                        unset($this->_employes[$idx]);
                    }
                }
                // verification pour une autre societe
                $sqlQuery = 'SELECT COUNT(us.user_id) AS nombre FROM '.PWE::getPrefixBdd().'user_societe AS us WHERE user_id='.$employe->getId();
                $results = bdd_sql::doSql($sqlQuery,true);
                if($results['count']>0){
                    if($results['results'][0]['nombre']==0){
                        $employe->delete();
                    }
                }
                
            }else{
                $retour['error'] = bdd_sql::$LASTERROR;
            }
        }
        return $retour;
    }
    
    /**
     * renvoi le tableau des propriétés de la societe
     * @param boolean $input
     * @return array
     */
    public function getDatas($input=false) {
        $data = array();
        $data['id'] = $this->getId();
        $data['nom'] = $this->getNom($input);
        $data['siret'] = $this->getSiret();
        $data['web'] = $this->getWeb();
        $data['email'] = $this->getEmail();
        $data['phone'] = $this->getPhone();
        $data['effectifs'] = $this->getEffectifs();
        $data['date_crea'] = $this->getDateCrea();
        $data['media'] = ($this->getMedia()!==null)?$this->getMedia():null;
        $data['adresse'] = ($this->getAdresse()!=null)?$this->getAdresse()->getDatas($input):null;
        $data['modele'] = 'societe';
        
        return $data;
    }
    public function setDatas($datas) {
        foreach($datas as $k=>$v){
            if(substr($k, 0, 1) !== '_') $k = '_'.$k;
            if($k != '_id' && property_exists('modules_societe_societe',$k)){
                $this->$k = $v;
            }
        }
        //adresse
        if($this->getAdresse()!==null){
            $adresse = $this->getAdresse();
        }else{
            $adresse = new modele_adresse();
        }
        $adresse->setDatas($datas);
        $this->_adresse = $adresse;
        
        //media
        if($this->getMedia()!=null)$this->getMedia()->setDatas($datas);
        
        return true;
    }
    
    /**
     * enregistrement de la fiche société
     * @return array
     */
    public function save(){
        if($this->getAdresse() !== null && $this->getAdresse()->getId()>0){
            $retour = $this->getAdresse()->update();
        }elseif($this->getAdresse() !== null){
            $retour = $this->getAdresse()->save();
        }
        if($retour['success']){
            $this->_adresse_id = $this->getAdresse()->getId();
        }
        
        $retour = array('success'=>false,'datas'=>array());
        
        $this->_date_crea = date("Y-m-d H:i:s");
        
        $sqlQuery = 'INSERT INTO '.self::getTable().' ';
        $sqlQuery .= '(nom,siret,web,email,phone,effectifs,adresse_id,date_crea) ';
        $sqlQuery .= 'VALUES (';
        $sqlQuery .= '"'.$this->getNom(true).'", ';
        $sqlQuery .= '"'.$this->getSiret().'", ';
        $sqlQuery .= '"'.$this->getWeb().'", ';
        $sqlQuery .= '"'.$this->getEmail().'", ';
        $sqlQuery .= '"'.$this->getPhone().'", ';
        $sqlQuery .= '"'.$this->getEffectifs().'", ';
        $sqlQuery .= ($this->getAdresseId()>0)?$this->getAdresseId():"null";
        $sqlQuery .= ', ';
        $sqlQuery .= '"'.$this->_date_crea.'")';
        
        $result = bdd_sql::doSql($sqlQuery,false);
        if($result['count']>0){
            $this->setId(bdd_sql::getLastInsertId());
            $retour['success'] = true;
            $retour['datas'] = $this->getDatas();
        }else{
            $retour['error'] = bdd_sql::$LASTERROR;
            $this->getAdresse()->delete();
        }
        return $retour;
    }
    /**
     * mise à jour de la fiche société
     * @return array
     */
    public function update(){
        //adresse
        if($this->getAdresse() !== null && $this->getAdresse()->getId()>0){
            $retour = $this->getAdresse()->update();
        }elseif($this->getAdresse() !== null){
            $retour = $this->getAdresse()->save();
        }
        if($retour['success']){
            $this->_adresse_id = $this->getAdresse()->getId();
        }
        
        $sqlQuery = 'UPDATE '.self::getTable().' SET ';
        $sqlQuery .= 'nom="'.$this->getNom(true).'",';
        $sqlQuery .= 'siret="'.$this->getSiret().'",';
        $sqlQuery .= 'web="'.$this->getWeb().'",';
        $sqlQuery .= 'email="'.$this->getEmail().'",';
        $sqlQuery .= 'phone="'.$this->getPhone().'",';
        $sqlQuery .= 'effectifs="'.$this->getEffectifs().'",';
        $sqlQuery .= 'adresse_id=';
        $sqlQuery .= ($this->getAdresseId()>0)?$this->getAdresseId():"null";
        $sqlQuery .= ' WHERE id='.$this->_id.' LIMIT 1';
        
        bdd_sql::doSql($sqlQuery,false);
        
        //media
        if($this->getMedia()!=null)$this->getMedia()->update();

        return array('success'=>true,'datas'=>$this->getDatas());
    }
    /**
     * suppression de la fiche société + adresse, média et employés
     * @return array
     */
    public function delete() {
        $sqlQuery = 'DELETE FROM '.self::getTable().' WHERE id='.$this->getId().' LIMIT 1';
        $result = bdd_sql::doSql($sqlQuery);
        if($result['count']>0){
            $sqlQueryEmp = 'DELETE FROM '.PWE::getPrefixBdd().'user_societe WHERE societe_id='.$this->getId().' LIMIT 1';
            bdd_sql::doSql($sqlQueryEmp);
            
            if($this->getAdresse()!==null)$this->getAdresse()->delete();
            if($this->getMedia()!==null)$this->getMedia()->delete();
            
            //TODO supression des employés
            if(count($this->getEmployes())>0){
                foreach ($this->getEmployes() as $employe){
                    $this->removeEmploye($employe);
                }
            }
        }
        return array('success'=>($result['count']>0)?true:false,'datas'=>array());
    }
    
    /* methodes statiques */
    /**
     * retourne le nom de la table prefixé
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    /**
     * renvoi la liste des sociétés
     * @param int $start
     * @param int $limit
     * @return \modules_societe_societe
     */
    public static function getListe($start=0,$limit=0){
        $sqlQuery = 'SELECT s.id FROM '.self::getTable().' AS s ORDER BY s.nom';
        
        if($limit>0){
            $sqlQuery .= ' LIMIT '.$start.','.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true,true);
        if($results['count']>0){
            foreach ($results['results'] as $data){
                $societe = new modules_societe_societe($data['id']);
                $retour[] = $societe;
            }
        }
        return $retour;
    }
    
    /**
     * renvoi le nombre total de sociétés
     * @return int
     */
    public static function getNombre(){
        $sqlQuery = 'SELECT COUNT(s.id) AS nombre FROM '.self::getTable().' AS s';
        $result = bdd_sql::doSql($sqlQuery);
        $nombre = 0;
        if($result['count']>0){
            $nombre = $result['results'][0]['nombre'];
        }
        
        return $nombre;
    }
    
}
